import reportService from '@/api/services/reportService';
import PagesHeader from '@/components/pages-header';
import Back from '@/components/router/Back';
import TabMenus from '@/pages/components/tab-menus/TabMenus';
import { useParams, useRouter } from '@/router/hooks';
import { KnowMenu } from '@/types/know/know';
import { RightOutlined, SearchOutlined } from '@ant-design/icons';
import { useDebounceFn } from 'ahooks';
import { Button, Input, message } from 'antd';
import { memo, useRef, useState } from 'react';
import ExportModal from './ExportModal';

interface Props {
  menus?: KnowMenu[];
  title?: string;
  selectedIndex?: number;
  onSearchTextChanged?: (text: string) => void;
  onChangeIndex?: (index: number) => void;
  onBack?: () => void;
  children?: React.ReactNode;
  canBack?: boolean;
  isRootDisplay?: boolean;
}

const SubPageHeader = ({
  menus,
  title = '',
  selectedIndex,
  onSearchTextChanged,
  onChangeIndex,
  onBack,
  children,
  canBack = true,
  isRootDisplay = true,
}: Props) => {
  const [searchText, setSearchText] = useState('');
  const [exportModalOpen, setExportModalOpen] = useState(false);
  const router = useRouter();

  const { run } = useDebounceFn(
    () => {
      onSearchTextChanged && onSearchTextChanged(searchText);
    },
    { wait: 500 },
  );

  const { appId = '' } = useParams() as {
    appId: string;
  };
  const [exportLoading, setExportloading] = useState(false);
  const abortControllerRef = useRef<AbortController | null>(null);

  const handleExport = async (startTime: string, endTime: string) => {
    console.log('导出数据', title, selectedIndex, startTime, endTime);
    try {
      setExportloading(true);
      // await new Promise(resolve => setTimeout(resolve, 10000)); // 模拟10秒的耗时
      const abortController = new AbortController();
      const { signal } = abortController;
      abortControllerRef.current = abortController;
      const res = await reportService.exportUnknownData(
        appId,
        startTime && endTime ? [startTime, endTime] : [],
        signal,
      );
      setExportloading(false);
      if (res?.download_url) {
        // 创建一个隐藏的a标签来下载文件
        const link = document.createElement('a');
        link.href = res.download_url;
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        // 清理DOM
        document.body.removeChild(link);
      } else {
        message.error('导出失败，获取下载链接失败');
      }
    } catch (error) {
      console.error('导出数据失败:', error);
      // message.error('导出数据失败')
    } finally {
      setExportloading(false);
    }
    setExportModalOpen(false);
  };

  return (
    <PagesHeader
      styles={{
        flexDirection: 'row',
      }}
    >
      {/* <div className="flex h-[52px] rounded-[15px] bg-[#FFF]"> */}
      {/* {canBack && <Back />} */}

      <div className="hidden items-center  md:flex">
        {isRootDisplay && (
          // <Button
          //   className="ml-[-10px] text-nowrap"
          //   type="text"
          //   style={{
          //     fontSize: 16,
          //     color: title !== '' ? '#86909C' : '#1D2129',
          //     fontWeight: title !== '' ? '' : 'bold',
          //   }}
          //   onClick={() => {
          //     onBack && onBack();
          //     // router.push('/know/know-gov');
          //   }}
          // >
          //   知识治理
          // </Button>

          <div
            className=" cursor-pointer text-nowrap"
            style={{
              fontSize: 16,
              color: title !== '' ? '#86909C' : '#1D2129',
              fontWeight: title !== '' ? '' : 'bold',
            }}
            onClick={() => {
              onBack && onBack();
              // router.push('/know/know-gov');
            }}
          >
            知识治理
          </div>
        )}
        {isRootDisplay && title !== '' && <div className="mx-2 text-[#C9CDD4]">/</div>}
        {title && (
          // <Button className="text-nowrap !px-[10px] text-[16px]" type="text">
          //   {isRootDisplay && <span className="text-[16px] font-bold text-[#1D2129]">{title}</span>}
          //   {!isRootDisplay && (
          //     <span className="text-[16px] font-medium text-[#474C5F]">{title}</span>
          //   )}
          // </Button>
          <div className="cursor-pointer text-nowrap text-[16px]">
            {isRootDisplay && <span className="text-[16px] font-bold text-[#1D2129]">{title}</span>}
            {!isRootDisplay && (
              <span className="text-[16px] font-medium text-[#474C5F]">{title}</span>
            )}
          </div>
        )}
      </div>

      {/* <TabMenus
        menus={menus}
        selectedIndex={selectedIndex}
        onChange={(index) => onChangeIndex && onChangeIndex(index)}
        className="w-full flex-1"
      />
      {onSearchTextChanged && (
        <div className="hidden items-center gap-2 md:flex">
          <Input
            style={{ border: 'none', background: '#fff' }}
            placeholder="搜索..."
            className="text-sm"
            value={searchText}
            prefix={<SearchOutlined style={{ color: '#C9CEE2', marginRight: '10px' }} />}
            onChange={(e) => {
              setSearchText(e.target.value);
              run();
            }}
          />

          {selectedIndex == 0 && title == '问题处理' && (
            <Button
              className="mx-2"
              type="primary"
              loading={exportLoading}
              onClick={() => setExportModalOpen(true)}
            >
              一键导出
            </Button>
          )}

          {children}

          <ExportModal
            open={exportModalOpen}
            onCancel={() => {
              // 如果有未完成的请求,取消
              if (abortControllerRef.current) {
                abortControllerRef.current.abort();
                exportLoading && message.info('任务已取消');
              }
              setExportModalOpen(false);
              setExportloading(false);
            }}
            onOk={handleExport}
            loading={exportLoading}
          />
        </div>
      )} */}
      {/* </div> */}
    </PagesHeader>
  );
};

export default memo(SubPageHeader);
